package com.example.demo.tools;

import com.example.demo.dao.ClassMemberDao;
import com.example.demo.dao.ClassesDao;
import com.example.demo.entity.pojo.ClassMember;
import com.example.demo.entity.pojo.Classes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 班级查询工具
 */
@Component
public class ClassTool {

    @Autowired
    private ClassesDao classesDao;

    @Autowired
    private ClassMemberDao classMemberDao;

    /**
     * 查询班级信息
     */
    public Map<String, Object> queryClass(Map<String, Object> params, String userId, String sessionId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String action = (String) params.get("action");
            
            switch (action) {
                case "all":
                    // 查询所有班级
                    List<Classes> allClasses = classesDao.queryAll();
                    result.put("classes", allClasses);
                    result.put("count", allClasses.size());
                    break;
                    
                case "my":
                    // 查询我的班级
                    List<ClassMember> myMembers = classMemberDao.queryByUserId(userId);
                    List<Classes> myClasses = new java.util.ArrayList<>();
                    for (ClassMember member : myMembers) {
                        Classes classes = classesDao.queryById(member.getClassId());
                        if (classes != null) {
                            myClasses.add(classes);
                        }
                    }
                    result.put("classes", myClasses);
                    result.put("count", myClasses.size());
                    break;
                    
                case "members":
                    // 查询班级成员
                    Integer classId = (Integer) params.get("class_id");
                    if (classId == null) {
                        throw new IllegalArgumentException("查询成员时必须提供班级ID");
                    }
                    
                    Classes classInfo = classesDao.queryById(classId);
                    List<ClassMember> members = classMemberDao.queryByClassId(classId);
                    
                    result.put("class", classInfo);
                    result.put("members", members);
                    result.put("memberCount", members.size());
                    break;
                    
                default:
                    throw new IllegalArgumentException("不支持的查询类型: " + action);
            }
            
        } catch (Exception e) {
            result.put("error", e.getMessage());
        }
        
        return result;
    }
}
